package org.lagou.interceptor;

import org.lagou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        if (handler instanceof HandlerMethod) {

            // 验证登录
            if (((HandlerMethod) handler).hasMethodAnnotation(LoginVerify.class)) {
                if (!verifyLogin(request, response, (HandlerMethod) handler)) {
                    return false;
                }
            }
        }
        return true;
    }
    private boolean verifyLogin (HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) {
        if (userService.isLogin(request)) {
             response.addCookie(new Cookie("token", userService.getToken(request)));
            return true;
        }
        if (handler.hasMethodAnnotation(ResponseBody.class)) {
            userService.loginFailJsonOut(response);
        } else {
            userService.loginFailJump(request, response);
        }
        return false;
    }
}
